<template>
  <div class="render" ref="mathjaxContainer" v-html="tomarked(myHtml)"></div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { marked } from 'marked';

const props = defineProps({
  text: {
    type: String,
    default: '',
    required: true,
  },
});

const tomarked = (text: string) => {
  return marked ? marked(text) : text;
};

const mathjaxContainer = ref<HTMLElement>();
const myHtml = ref('');
const mdi = new (window as any).markdownit({
  html: true,
  linkify: true,
});

const TypeSet = async (el?: HTMLElement) => {
  const MathJax = (window as any).MathJax;
  if (!MathJax || !el) return;
  await MathJax.startup.promise;
  await MathJax.typesetPromise([el]);
};

const render = async () => {
  // 自定义替换，把 \( 和 \) 转成 $ 语法
  const text = props.text.replace(/\\\(/g, '$').replace(/\\\)/g, '$');
  const formatText = mdi.render(text);
  myHtml.value = formatText;
  await nextTick(); // 等 DOM 更新完成
  TypeSet(mathjaxContainer.value); // MathJax 渲染公式
};

onMounted(() => {
  render();
});

watch(
  () => props.text,
  () => {
    render();
  },
);
</script>

<style scoped>
.render {
}
</style>
